//
//  NSObject+LeavLightAPI.m
//  LeaveLight
//
//  Created by 张 on 2019/3/8.
//  Copyright © 2019年 xsl. All rights reserved.
//

#import "NSObject+LeavLightAPI.h"

@implementation NSObject (LeavLightAPI)

/**
 * 版本检测更新
 * @param successBlock       成功回调（）
 * @param failedBlock        失败回调（error:错误信息）
 * @return
 */
- (void)checkAppUpdateSuccess:(void (^) (NSDictionary * value))successBlock
                       failed:(void (^)(NSString *error))failedBlock
{
    BADataEntity *entity = [BADataEntity new];
    entity.urlString = [BASEURL stringByAppendingString:@"v1/index/startup"];
    entity.needCache = NO;
    entity.parameters = [self dictionaryEncryotionWithParameterDic:@{}];
    [BANetManager ba_request_POSTWithEntity:entity successBlock:^(id response) {
        NSLog(@"get 请求数据结果： *** %@", response);
        NSInteger code = [[response objectForKey:@"code"] integerValue];
        if (code == 200) {
            successBlock(response[@"data"]);
        }else{
            failedBlock([response objectForKey:@"msg"]);
        }
    } failureBlock:^(NSError *error) {
        failedBlock(error.localizedDescription);
    } progressBlock:nil];
}

/**
 微信登录
 
 @param successBlock 登陆成功
 @param failedBlock 失败返回信息
 */
- (void)wxLoginWithUid:(NSString *)uid
                   img:(NSString *)img
                   sex:(NSString *)sex
              nickName:(NSString *)name
               Success:(void (^) (void))successBlock
                failed:(void (^)(NSString *error))failedBlock
{
    NSDictionary *parameters = @{
                                 @"unionid":uid,@"avatar":img,@"gender":sex,@"nickname":name
                                 };
    BADataEntity *entity = [BADataEntity new];
    entity.urlString = [BASEURL stringByAppendingString:@"v1/user/wechat"];
    entity.needCache = NO;
    entity.parameters = [self dictionaryEncryotionWithParameterDic:parameters];
    
    // 如果打印数据不完整，是因为 Xcode 8 版本问题，请下断点打印数据
    [BANetManager ba_request_POSTWithEntity:entity successBlock:^(id response) {
        NSLog(@"post 请求数据结果： *** %@", response);
        NSInteger code = [[response objectForKey:@"code"] integerValue];
        if (code == 200) {
            [UserDefaults setUserID:[NSString stringWithFormat:@"%@",[[[response objectForKey:@"data"] objectForKey:@"user"] objectForKey:@"id"]]];
            [UserDefaults setAccessToken:[[response objectForKey:@"data"] objectForKey:@"token"]];
            successBlock();
        }else{
            failedBlock([response objectForKey:@"msg"]);
        }
    } failureBlock:^(NSError *error) {
        failedBlock(error.localizedDescription);
    } progressBlock:^(int64_t bytesProgress, int64_t totalBytesProgress) {
    }];
}

/**
 游客登录
 
 @param successBlock 登陆成功
 @param failedBlock 失败返回信息
 */
- (void)iphoneLoginWithUid:(NSString *)uid
                   Success:(void (^) (void))successBlock
                    failed:(void (^)(NSString *error))failedBlock
{
    NSDictionary *parameters = @{
                                 @"unionid":uid
                                 };
    BADataEntity *entity = [BADataEntity new];
    entity.urlString = [BASEURL stringByAppendingString:@"v1/user/loginDevice"];
    entity.needCache = NO;
    entity.parameters = [self dictionaryEncryotionWithParameterDic:parameters];
    
    // 如果打印数据不完整，是因为 Xcode 8 版本问题，请下断点打印数据
    [BANetManager ba_request_POSTWithEntity:entity successBlock:^(id response) {
        NSLog(@"post 请求数据结果： *** %@", response);
        NSInteger code = [[response objectForKey:@"code"] integerValue];
        if (code == 200) {
            [UserDefaults setUserID:[NSString stringWithFormat:@"%@",[[[response objectForKey:@"data"] objectForKey:@"user"] objectForKey:@"id"]]];
            [UserDefaults setAccessToken:[[response objectForKey:@"data"] objectForKey:@"token"]];
            [UserDefaults setUserImage:[[[response objectForKey:@"data"] objectForKey:@"user"] objectForKey:@"avatar"]];
            [UserDefaults setUserRealName:[[[response objectForKey:@"data"] objectForKey:@"user"] objectForKey:@"nickname"]];
            successBlock();
        }else{
            failedBlock([response objectForKey:@"msg"]);
        }
    } failureBlock:^(NSError *error) {
        failedBlock(error.localizedDescription);
    } progressBlock:^(int64_t bytesProgress, int64_t totalBytesProgress) {
    }];
}



/**
 * 发现栏目 - 分类
 * @param successBlock       成功回调（）
 * @param failedBlock        失败回调（error:错误信息）
 * @return
 */
- (void)getFundTypeListSuccess:(void (^) (NSMutableArray *typeArr))successBlock
                        failed:(void (^)(NSString *error))failedBlock
{
    NSDictionary *parameters = @{};
    BADataEntity *entity = [BADataEntity new];
    entity.urlString = [BASEURL stringByAppendingString:@"v1/index/getAllCategory"];
    entity.needCache = YES;
    entity.parameters = [self dictionaryEncryotionWithParameterDic:parameters];
    
    // 如果打印数据不完整，是因为 Xcode 8 版本问题，请下断点打印数据
    [BANetManager ba_request_POSTWithEntity:entity successBlock:^(id response) {
        NSLog(@"post 请求数据结果： *** %@", response);
        NSInteger code = [[response objectForKey:@"code"] integerValue];
        if (code == 200) {
            successBlock([[response objectForKey:@"data"] objectForKey:@"list"]);
        }else{
            failedBlock([response objectForKey:@"msg"]);
        }
    } failureBlock:^(NSError *error) {
        failedBlock(error.localizedDescription);
    } progressBlock:^(int64_t bytesProgress, int64_t totalBytesProgress) {
    }];
}

/**
 首页 - 发现 - 列表数据
 @param categoryID 分类ID
 @param successBlock 数据列表
 @param failedBlock 失败回调（error:错误信息）
 */
- (void)getLeavelightListWithcategoryid:(NSString *)categoryID
                                Success:(void (^) (NSMutableArray * listArr))successBlock
                                 failed:(void (^)(NSString *error))failedBlock
{
    
    NSDictionary *parameters = @{@"category_id":categoryID,@"number":@(20),@"user_id":[UserDefaults getUserID]};
    BADataEntity *entity = [BADataEntity new];
    entity.urlString = [BASEURL stringByAppendingString:@"v1/index/getRandData"];
    entity.needCache = NO;
    entity.parameters = [self dictionaryEncryotionWithParameterDic:parameters];
    
    // 如果打印数据不完整，是因为 Xcode 8 版本问题，请下断点打印数据
    [BANetManager ba_request_POSTWithEntity:entity successBlock:^(id response) {
        NSLog(@"post 请求数据结果： *** %@", response);
        NSInteger code = [[response objectForKey:@"code"] integerValue];
        if (code == 200) {
            NSMutableArray * listarr = [NSMutableArray array];
            NSArray * arr = [[response objectForKey:@"data"] objectForKey:@"list"];
            for (NSDictionary * dic in arr) {
                ZDBaseModel * model = [ZDBaseModel mj_objectWithKeyValues:dic];
                if (model.content.length > 50) {
                    model.template_type = (arc4random() % 2) + 7;
                }
                [listarr addObject:model];
            }
            successBlock(listarr);
        }else{
            failedBlock([response objectForKey:@"msg"]);
        }
    } failureBlock:^(NSError *error) {
        failedBlock(error.localizedDescription);
    } progressBlock:^(int64_t bytesProgress, int64_t totalBytesProgress) {
    }];
}

/**
 * 鸡汤详情
 * @param successBlock       成功回调（）
 * @param failedBlock        失败回调（error:错误信息）
 * @return
 */
- (void)getChickenDetailWithid:(NSString *)chicken_id
                       Success:(void (^) (ZDBaseModel * model))successBlock
                         failed:(void (^)(NSString *error))failedBlock
{
    NSDictionary *parameters = @{@"chicken_id":chicken_id,@"user_id":[UserDefaults getUserID]};
    BADataEntity *entity = [BADataEntity new];
    entity.urlString = [BASEURL stringByAppendingString:@"v1/index/getChickenDetail"];
    entity.needCache = YES;
    entity.parameters = [self dictionaryEncryotionWithParameterDic:parameters];
    
    // 如果打印数据不完整，是因为 Xcode 8 版本问题，请下断点打印数据
    [BANetManager ba_request_POSTWithEntity:entity successBlock:^(id response) {
        NSLog(@"post 请求数据结果： *** %@", response);
        NSInteger code = [[response objectForKey:@"code"] integerValue];
        if (code == 200) {
            successBlock([ZDBaseModel mj_objectWithKeyValues:[response objectForKey:@"data"]]);
        }else{
            failedBlock([response objectForKey:@"msg"]);
        }
    } failureBlock:^(NSError *error) {
        failedBlock(error.localizedDescription);
    } progressBlock:^(int64_t bytesProgress, int64_t totalBytesProgress) {
    }];
}

#pragma mark - 收藏

/**
 获取收藏列表
 @param successBlock 数据列表
 @param failedBlock 失败回调（error:错误信息）
 */
- (void)getCollectListWithPagesize:(NSInteger)pagesize index:(NSInteger)index
                              Success:(void (^) (NSMutableArray * listArr))successBlock
                               failed:(void (^)(NSString *error))failedBlock
{
    
    if (CLIENT.isLogin == NO) {
        LoginController * login = [[LoginController alloc]initWithNibName:@"LoginController" bundle:nil];
        [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:login animated:YES completion:^{
        }];
        return;
    }
    
    NSDictionary *parameters = @{@"user_id":[UserDefaults getUserID],@"page_size":@(20),@"page_number":@(index)};
    BADataEntity *entity = [BADataEntity new];
    entity.urlString = [BASEURL stringByAppendingString:@"v1/usercenter/getAllCollect"];
    entity.needCache = YES;
    entity.parameters = [self dictionaryEncryotionWithParameterDic:parameters];
    
    // 如果打印数据不完整，是因为 Xcode 8 版本问题，请下断点打印数据
    [BANetManager ba_request_POSTWithEntity:entity successBlock:^(id response) {
        NSLog(@"post 请求数据结果： *** %@", response);
        NSInteger code = [[response objectForKey:@"code"] integerValue];
        if (code == 200) {
            NSMutableArray * listarr = [NSMutableArray array];
            NSArray * arr = [[response objectForKey:@"data"] objectForKey:@"list"];
            for (NSDictionary * dic in arr) {
                CollectModel * model = [CollectModel mj_objectWithKeyValues:dic];
                model.chicken_data = [ZDBaseModel mj_objectWithKeyValues:dic[@"chicken_data"]];
                [listarr addObject:model];
            }
            successBlock(listarr);
        }else{
            failedBlock([response objectForKey:@"msg"]);
        }
    } failureBlock:^(NSError *error) {
        failedBlock(error.localizedDescription);
    } progressBlock:^(int64_t bytesProgress, int64_t totalBytesProgress) {
    }];
}

/**
 * 增加到收藏
 * @param successBlock       成功回调（）
 * @param failedBlock        失败回调（error:错误信息）
 * @return
 */
- (void)addCollectWithid:(NSString *)chicken_id
                  imgUrl:(NSString *)imgUrl
           template_type:(NSInteger )template_type
                 Success:(void (^) (void))successBlock
                  failed:(void (^)(NSString *error))failedBlock
{
    
    if (CLIENT.isLogin == NO) {
        LoginController * login = [[LoginController alloc]initWithNibName:@"LoginController" bundle:nil];
        [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:login animated:YES completion:^{
        }];
        return;
    }
    
    NSDictionary *parameters = @{@"chicken_id":chicken_id,@"user_id":[UserDefaults getUserID],@"image_url":imgUrl,@"template_type":@(template_type)};
    BADataEntity *entity = [BADataEntity new];
    entity.urlString = [BASEURL stringByAppendingString:@"v1/usercenter/addCollect"];
    entity.needCache = YES;
    entity.parameters = [self dictionaryEncryotionWithParameterDic:parameters];
    
    // 如果打印数据不完整，是因为 Xcode 8 版本问题，请下断点打印数据
    [BANetManager ba_request_POSTWithEntity:entity successBlock:^(id response) {
        NSLog(@"post 请求数据结果： *** %@", response);
        NSInteger code = [[response objectForKey:@"code"] integerValue];
        if (code == 200) {
            successBlock();
        }else{
            failedBlock([response objectForKey:@"msg"]);
        }
    } failureBlock:^(NSError *error) {
        failedBlock(error.localizedDescription);
    } progressBlock:^(int64_t bytesProgress, int64_t totalBytesProgress) {
    }];
}

/**
 * 删除收藏
 * @param successBlock       成功回调（）
 * @param failedBlock        失败回调（error:错误信息）
 * @return
 */
- (void)deleteCollectWithid:(NSString *)chicken_id
                    Success:(void (^) (void))successBlock
                     failed:(void (^)(NSString *error))failedBlock
{
    
    if (CLIENT.isLogin == NO) {
        LoginController * login = [[LoginController alloc]initWithNibName:@"LoginController" bundle:nil];
        [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:login animated:YES completion:^{
        }];
        return;
    }
    
    NSDictionary *parameters = @{@"chicken_id":chicken_id,@"user_id":[UserDefaults getUserID]};
    BADataEntity *entity = [BADataEntity new];
    entity.urlString = [BASEURL stringByAppendingString:@"v1/usercenter/delCollect"];
    entity.needCache = YES;
    entity.parameters = [self dictionaryEncryotionWithParameterDic:parameters];
    
    // 如果打印数据不完整，是因为 Xcode 8 版本问题，请下断点打印数据
    [BANetManager ba_request_POSTWithEntity:entity successBlock:^(id response) {
        NSLog(@"post 请求数据结果： *** %@", response);
        NSInteger code = [[response objectForKey:@"code"] integerValue];
        if (code == 200) {
            successBlock();
        }else{
            failedBlock([response objectForKey:@"msg"]);
        }
    } failureBlock:^(NSError *error) {
        failedBlock(error.localizedDescription);
    } progressBlock:^(int64_t bytesProgress, int64_t totalBytesProgress) {
    }];
}

#pragma mark - 用户反馈

/**
 获取所有反馈列表
 @param successBlock 数据列表
 @param failedBlock 失败回调（error:错误信息）
 */
- (void)getUserCommentListSuccess:(void (^) (NSMutableArray * listArr))successBlock
                           failed:(void (^)(NSString *error))failedBlock
{
    if (CLIENT.isLogin == NO) {
        LoginController * login = [[LoginController alloc]initWithNibName:@"LoginController" bundle:nil];
        [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:login animated:YES completion:^{
        }];
        return;
    }
    
    NSDictionary *parameters = @{@"user_id":[UserDefaults getUserID]};
    BADataEntity *entity = [BADataEntity new];
    entity.urlString = [BASEURL stringByAppendingString:@"v1/usercenter/getAllFeedbackData"];
    entity.needCache = YES;
    entity.parameters = [self dictionaryEncryotionWithParameterDic:parameters];
    
    // 如果打印数据不完整，是因为 Xcode 8 版本问题，请下断点打印数据
    [BANetManager ba_request_POSTWithEntity:entity successBlock:^(id response) {
        NSLog(@"post 请求数据结果： *** %@", response);
        NSInteger code = [[response objectForKey:@"code"] integerValue];
        if (code == 200) {
            NSMutableArray * listarr = [NSMutableArray array];
            NSArray * arr = [[response objectForKey:@"data"] objectForKey:@"list"];
            for (NSDictionary * dic in arr) {
                FeedBackModel * model = [FeedBackModel mj_objectWithKeyValues:dic];
                [model toCalculateCellHeight];
                [listarr addObject:model];
            }
            successBlock(listarr);
        }else{
            failedBlock([response objectForKey:@"msg"]);
        }
    } failureBlock:^(NSError *error) {
        failedBlock(error.localizedDescription);
    } progressBlock:^(int64_t bytesProgress, int64_t totalBytesProgress) {
    }];
}

/**
 * 增加到反馈
 * @param successBlock       成功回调（）
 * @param failedBlock        失败回调（error:错误信息）
 * @return
 */
- (void)addCommentWithContent:(NSString *)content
                      Success:(void (^) (void))successBlock
                       failed:(void (^)(NSString *error))failedBlock
{
    if (CLIENT.isLogin == NO) {
        LoginController * login = [[LoginController alloc]initWithNibName:@"LoginController" bundle:nil];
        [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:login animated:YES completion:^{
        }];
        return;
    }
    NSDictionary *parameters = @{@"content":content,@"user_id":[UserDefaults getUserID]};
    BADataEntity *entity = [BADataEntity new];
    entity.urlString = [BASEURL stringByAppendingString:@"v1/usercenter/addUserFeedback"];
    entity.needCache = YES;
    entity.parameters = [self dictionaryEncryotionWithParameterDic:parameters];
    // 如果打印数据不完整，是因为 Xcode 8 版本问题，请下断点打印数据
    [BANetManager ba_request_POSTWithEntity:entity successBlock:^(id response) {
        NSLog(@"post 请求数据结果： *** %@", response);
        NSInteger code = [[response objectForKey:@"code"] integerValue];
        if (code == 200) {
            successBlock();
        }else{
            failedBlock([response objectForKey:@"msg"]);
        }
    } failureBlock:^(NSError *error) {
        failedBlock(error.localizedDescription);
    } progressBlock:^(int64_t bytesProgress, int64_t totalBytesProgress) {
    }];
}





#pragma mark - sign
/**
 获取加密后的参数字典

 @param parameter 原参数集合
 @return 加密后的参数集合
 */
- (NSDictionary *)dictionaryEncryotionWithParameterDic:(NSDictionary *)parameter
{
    NSMutableDictionary * newDic = [NSMutableDictionary dictionaryWithDictionary:parameter];
    
    int rand = arc4random() % 10000;
    NSTimeInterval time = [[NSDate dateWithTimeIntervalSinceNow:0] timeIntervalSince1970];
    [newDic setObject:[NSString stringWithFormat:@"%.0f", time] forKey:@"timestamp"];
    [newDic setObject:@(rand) forKey:@"rand"];
    NSString * sign = [self signWithDic:newDic];
    [newDic setObject:sign forKey:@"sign"];
    return newDic;
}


- (NSString *)signWithDic:(NSDictionary *)dic
{
    NSArray * arr = dic.allKeys;
    NSStringCompareOptions comparisonOptions = NSCaseInsensitiveSearch|NSNumericSearch|
    NSWidthInsensitiveSearch|NSForcedOrderingSearch;
    NSComparator sort = ^(NSString *obj1,NSString *obj2){
        NSRange range = NSMakeRange(0,obj1.length);
        return [obj1 compare:obj2 options:comparisonOptions range:range];
    };
    NSArray *resultArray = [arr sortedArrayUsingComparator:sort];
    
    
    NSMutableArray * newArr = [NSMutableArray array];
    for (NSString * key in resultArray) {
        NSString * str = [NSString stringWithFormat:@"%@=%@",key,[dic objectForKey:key]];
        [newArr addObject:str];
    }
    return [self HmacSha1data:[newArr componentsJoinedByString:@"&"]];
}

- (NSString *)HmacSha1data:(NSString *)data
{
    const char *cKey  = [SIGNKEY cStringUsingEncoding:NSUTF8StringEncoding];
    const char *cData = [data cStringUsingEncoding:NSUTF8StringEncoding];
    
    //sha1
    unsigned char cHMAC[CC_SHA1_DIGEST_LENGTH];
    CCHmac(kCCHmacAlgSHA1, cKey, strlen(cKey), cData, strlen(cData), cHMAC);
    
    NSData *HMAC = [[NSData alloc] initWithBytes:cHMAC
                                          length:sizeof(cHMAC)];
    
    NSString *hash = [HMAC base64EncodedStringWithOptions:0];//将加密结果进行一次BASE64编码。
    return hash;
}

@end
